package com.ptswitch.material.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Hibernate;
import org.hxzon.project.AbstractModelService;
import org.hxzon.util.BitUtil;
import org.hxzon.util.NumberFormatUtil;
import org.hxzon.util.StringUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.service.MaterialService;

@Service
public class MaterialServiceImpl extends AbstractModelService<Material> implements MaterialService {

    public void saveAll(Collection<Material> newMaterials, Collection<Material> oldMaterials, Collection<Material> updateMaterials) {
        dao.saveAll(newMaterials);
        dao.deleteAll(oldMaterials);
        dao.saveAll(updateMaterials);
    }

    public void delete(Material model) {
        if (!model.getBomMaterials().isEmpty()) {
            return;
        }
        // uploadDao.deleteAll(model.getUploads());
        dao.delete(model);
    }

    public Material findById(String id, int init) {
        Material material = dao.findById(Material.class, id);
        if (material != null) {
            if (BitUtil.isSet(init, Init_BomMaterials)) {
                Hibernate.initialize(material.getBomMaterials());
            }
            if (BitUtil.isSet(init, Init_Uploads)) {
                Hibernate.initialize(material.getAttachments());
            }
            if (BitUtil.isSet(init, Init_ContractItems)) {
                Hibernate.initialize(material.getContractItems());
            }
        }
        return material;
    }

    public Material findByCode(String code) {
        code = StringUtil.escapeSql(code);
        return dao.findOne(Material.class, " where p.code='" + code + "'");
    }

    public List<Material> findByPcbDecal(String pcbDecal) {
        pcbDecal = StringUtil.escapeSql(pcbDecal);
        return dao.findList(Material.class, " where p.pcbDecal='" + pcbDecal + "'", -1, -1);
    }

    public boolean existPcbDecal(String pcbDecal) {
        long count = dao.countList(Material.class, " where p.pcbDecal='" + pcbDecal + "'");
        // logger.debug("{}",count);
        return count > 0;
    }

    public List<Material> findList(String fieldName, String fieldValue, long first, long size) {
        return dao.findList(Material.class, fieldName, fieldValue, first, size);
    }

    public long countList(String fieldName, Object fieldValue) {
        return dao.countList(Material.class, fieldName, fieldValue);
    }

    public void save(Material model) {
        String state = model.getState();
        if (state == null || state.isEmpty()) {
            state = "一般";
        }
        if (state.equals("推荐") || state.equals("一般") || state.equals("不推荐") || state.equals("停用") || state.equals("未发布")) {

        } else {
            state = state + "描述不规范，请检查";
        }
        model.setState(state);
        dao.save(model);
    }

    public void saveAll(List<Material> models) {
        for (Material model : models) {
            save(model);
        }
    }

    private Pattern p = Pattern.compile(".*-(\\d*)-.*");

    public String emptyCode(String code) {
        code = StringUtil.escapeSql(code);
        List<String> list = (List<String>) dao.query("select p.code from Material as p where p.code like '" + code + "-%' order by p.code", -1, -1);// code-%
        if (list.isEmpty()) {
            return code + "-000-0";
        }
        String lastCode = list.get(list.size() - 1);
        logger.debug("get empty code:{}", lastCode);
        Matcher m = p.matcher(lastCode);
        try {
            m.matches();
            int index = Integer.parseInt(m.group(1)) + 1;
            return code + "-" + NumberFormatUtil.format(index, "000") + "-0";
        } catch (RuntimeException e) {
            logger.error("get empty code fail", e);
        }
        return code;
    }

    public String valid(Material model) {
        return null;
    }

}
